package handler

import (
	"encoding/json"
	"novel-fuan-/cache"
	"novel-fuan-/models"
	"novel-fuan-/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误超过3次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误3次,禁止两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return
}
func List(c *gin.Context) {
	var book []models.Book
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}
	var total int64
	models.DB.Model(models.Book{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  book,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var book models.Book
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": book,
	})
	return
}
func CommitAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Book{
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误",
		})
		return
	}
	var book models.Book
	redis_key := "Add_" + title
	models.DB.Where("id=?", data.ID).Find(&book).Order(data)
	jsonData, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
